<template>
  <div class="picking zy-content">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="6">
          <div>
            <p class="label">{{ $t('equipmentscrapped.Location') }}</p>
            <div class="ipt">
              <Cascader v-model="searchParams.installPosition" @on-change="orgChange" :data="orgList"/>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('equipCheck.SerialNo') }}</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.deviceMId"
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}${$t('equipCheck.SerialNo')}`"
                  :remote-method="remoteMethodDeviceMId"
              >
                <Option
                    v-for="item of devNoList"
                    :value="item.deviceMId"
                    :key="item.deviceMId"
                    :label="item.deviceMId + '-' + item.deviceName"
                ></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('equipmentscrapped.AssetNo') }}</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.assetCode"
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}${$t('equipmentscrapped.AssetNo')}`"
                  :remote-method="remoteMethodassetCode"
              >
                <Option
                    v-for="item of devNoList"
                    :value="item.assetCode"
                    :key="item.assetCode"
                    :label="item.assetCode + '-' + item.deviceName"
                ></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('equipmentscrapped.EquipmentNo') }}</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.deviceNo"
                  filterable
                  label-in-value
                  clearable
                  :remote-method="searchDevice"
                  :placeholder="$t('maintenance.EquipmentNo')"
              >
                <Option
                    v-for="(item, index) of deviceList"
                    :value="item.deviceNo"
                    :key="index"
                    :label="item.deviceNo + '-' + item.deviceName"
                ></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('SystemConfig.shift') }}</p>
            <div class="ipt">
              <Select v-model="searchParams.shiftId" clearable
                      :placeholder="`${$t('common.selectInfo')}${$t('SystemConfig.shift')}`">
                <Option v-for="(item, index) of productionShiftList" :value="item.id" :label="item.shift"
                        :key="index"></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="6">
          <div>
            <p class="label">{{ $t('common.Date') }}</p>
            <div class="ipt">
              <DatePicker
                  type="daterange"
                  v-model="timeList"
                  split-panels
                  placement="bottom"
                  transfer
                  valueFormatter="yyyy-MM-dd"
                  :placeholder="`${$t('common.selectInfo')}${$t('common.Date')}`"
                  :clearable="false"
              ></DatePicker>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">设备类别</p>
            <div class="ipt">
              <Select
                  v-model="searchParams.deviceCategory"
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}设备类别`"
              >
                <Option v-for="val in deviceType" :value="val.value" :key="val" :label="val.value"></Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="5">
          <div class="t-c">
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button type="primary" class="search-btn" @click="changeNum()">{{ $t('common.Query') }}</Button>
              <Button class="reset-btn" @click="reset()">{{ $t('common.reset') }}</Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>

    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>

        <Button @click="exportTemplateClick">{{ $t('common.batchExport') }}</Button>
      </div>

      <div class="tableContent">
        <Table
            class="resizable-table"
            border
            @on-column-width-resize="onColumnWidthResize"
            ellipsis
            ref="selection"
            @on-selection-change="handleSelectionChange"
            :columns="columns"
            :data="dataArr"
        >
        </Table>
      </div>

      <div class="pageWrap mt16">
        <pageLeftTitle :total="total"/>
        <Page
            :total="total"
            :page-size="pageSize"
            :page-size-opts="$variable.pageSizes"
            :current="pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
        />
      </div>
    </div>
  </div>
</template>

<script>
import fileDownload from 'js-file-download';
import {getDeviceListinfo} from '@/api/maintenance';
import recursion from '@/util/recursion';
import {getDictData} from '@/api/index.js';
import toggleTableOperation from '@/mixins/toggleTableOperation';

export default {
  name: 'oeelose',
  mixins: [toggleTableOperation],
  data() {
    return {
      deviceList: [],
      productionShiftList: [],
      selectRows: [],
      timeList: [this.$moment(new Date()).subtract(6, 'days').format('YYYY-MM-DD'), this.$moment(new Date()).format('YYYY-MM-DD')],
      classArr: [],
      equipmentList: [],
      hierarchyList: [],
      searchParams: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      pageSizeOption: [10, 20, 30, 40],
      columns: [
        {
          // title: "日期",
          title: `${this.$t('common.Date')}`,
          key: 'scheduleDate',
          align: 'center',
          resizable: true,
        },
        {
          // title: "班次",
          title: `${this.$t('班次')}`,
          key: 'shift',
          align: 'center',
          resizable: true,
        },
        {
          // title: "安装位置",
          title: `${this.$t('安装位置')}`,
          key: 'factoryName',
          align: 'center',
          width: 220,
          resizable: true,
        },
        {
          // title: "设备名称",
          title: `${this.$t('设备名称')}`,
          key: 'deviceName',
          align: 'center',
          resizable: true,
        },
        {
          // title: "设备编号",
          title: `${this.$t('设备编号')}`,
          key: 'deviceNo',
          align: 'center',
          resizable: true,
        },
        {
          // title: "资产编号",
          title: `${this.$t('资产编号')}`,
          key: 'assetCode',
          align: 'center',
          resizable: true,
        },
        {
          // title: "设备流水号",
          title: `${this.$t('设备流水号')}`,
          minWidth: 200,
          key: 'deviceMId',
          align: 'center',
          resizable: true,
        },
        {
          title: 'OEE(%)',
          key: 'oee',
          align: 'center',
          resizable: true,
        },
        {
          // title: "计划运行时间(min)",
          title: `${this.$t('计划运行时间')}(min)`,
          key: 'durations',
          align: 'center',
          minWidth: 200,
          resizable: true,
        },
        {
          // title: "实际运行时间(min)",
          title: `${this.$t('实际运行时间')}(min)`,
          key: 'runningDuration',
          align: 'center',
          minWidth: 200,
          resizable: true,
        },
        {
          // title: "实际运行时间(min)",
          title: `${this.$t('异常工时汇总')}(min)`,
          key: 'totalShutdownDuration',
          align: 'center',
          minWidth: 200,
          resizable: true,
        },
        {
          // title: "待机时间(min)",
          title: `${this.$t('待机时间')}(min)`,
          key: 'waitDuration',
          align: 'center',
          minWidth: 200,
          resizable: true,
        },
        {
          // title: "断线时间(min)",
          title: `${this.$t('断线时间')}(min)`,
          key: 'offLineDuration',
          align: 'center',
          minWidth: 200,
          resizable: true,
        },
        {
          // title: "时间开动率(%)",
          title: '时间稼动率(%)',
          key: 'timeCropMovement',
          align: 'center',
          minWidth: 200,
          resizable: true,
        },

        {
          title: '性能稼动率(%)',
          key: 'performanceCropMovement',
          align: 'center',
          minWidth: 240,
          resizable: true,
        },
        {
          title: '生产数',
          key: 'output',
          align: 'center',
          minWidth: 200,
          resizable: true,
        },
        {
          title: '良品数',
          key: 'goodNum',
          align: 'center',
          minWidth: 200,
          resizable: true,
        },
        {
          title: '报废数',
          key: 'scrapCount',
          align: 'center',
          resizable: true,
        },
        {
          title: '人工作业时间',
          key: 'laborOperationTime',
          align: 'center',
          resizable: true,
          render: (h, params) => {
            return h('span',
                params.row.laborOperationTime + (params.row.laborUnit || '')
            );
          }
        },
        {
          title: '合格率(%)',
          key: 'passRate',
          align: 'center',
          resizable: true,
        },
        // {
        // 	title: 'NEE(%)',
        // 	key: 'nee',
        // 	align: 'center',
        // 	resizable: true,
        // },
        // {
        // 	title: 'U(%)',
        // 	key: 'u',
        // 	align: 'center',
        // 	resizable: true,
        // },
        // {
        // 	title: 'SPT(min)',
        // 	key: 'spt',
        // 	align: 'center',
        // 	resizable: true,
        // },
        // {
        // 	title: 'POT(min)',
        // 	key: 'pot',
        // 	align: 'center',
        // 	resizable: true,
        // },
      ],
      dataArr: [],
      devNoList: [],
      orgList: [],
      deviceType: [],
    };
  },
  created() {
    this.columns.forEach((m) => (m.minWidth ? '' : (m.minWidth = 150)));
    this.getColumnWidth(this.columns);
    getDictData('设备类别').then((res) => {
      this.deviceType = res.data;
    });
  },
  mounted() {
    this.getHierarchy();
    this.changeNum();
    this.getOrgList();
  },
  methods: {
    getOrgList() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {level: 1},
      }).then((res) => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'code',
            children: 'children',
          };
          this.orgList = recursion.convertTree(res.data, obj);
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    orgChange(val) {
      this.getShiftList(val);
    },
    getShiftList(val) {
      const workShop = val.at(-1);
      this.axios({
        method: 'get',
        url: '/dms/oee-board/selectShiftByWorkShop',
        params: {workShop},
      }).then((res) => {
        this.productionShiftList = res.data;
      });
    },
    searchDevice(query) {
      // let installPosition = '';
      // if (this.searchParams.installPosition && this.searchParams.installPosition.length > 0) {
      // 	installPosition = this.searchParams.installPosition.at(-1);
      // }
      getDeviceListinfo({
        deviceNo: query,
        pageSize: 200,
        pageNum: 1,
      }).then((res) => {
        if (res.code === 200) {
          this.deviceList = res.data.records;
        }
      });
    },
    remoteMethodassetCode(query) {
      if (query) {
        this.getassetCode(query);
      }
    },
    async getassetCode(item) {
      let param = {
        assetCode: item,
        deviceMId: '',
        deviceNo: '',
        pageSize: 200,
        pageNum: 1,
      };
      let {data, code, msg} = await getDeviceListinfo(param);
      if (code === 200) {
        this.devNoList = data.records;
      }
    },
    remoteMethodDeviceMId(query) {
      if (query) {
        this.getDeviceMId(query);
      }
    },
    async getDeviceMId(item) {
      let param = {
        // assetCode: '',
        deviceMId: item,
        pageSize: 200,
        pageNum: 1,
        // deviceNo: '',
        // orgCode: '',
      };
      let {data, code} = await getDeviceListinfo(param);
      if (code === 200) {
        this.devNoList = data.records;
      }
    },
    handleSelectionChange(selectionData) {
      let arr = [];
      selectionData.forEach((item) => {
        arr.push(item);
      });
      this.selectRows = arr;
    },
    getHierarchy() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {
          level: 3,
        },
      }).then((res) => {
        if (res.code == 200) {
          this.hierarchyList = this.getHierarchyByMachining(res.data);
        }
      });
    },
    getHierarchyByMachining(arr) {
      arr.forEach((item) => {
        item['value'] = item.code;
        item['label'] = item.name;
        if (item.children.length > 0) {
          this.getHierarchyByMachining(item.children);
        }
      });
      return arr;
    },
    reset() {
      this.searchParams = {};
      this.timeList = [this.$moment(new Date()).subtract(6, 'days').format('YYYY-MM-DD'), this.$moment(new Date()).format('YYYY-MM-DD')];
      this.changeNum();
    },
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList() {
      //查询列表
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams,
      };

      if (this.timeList[1]) {
        params.startDate = this.$moment(this.timeList[0]).format('YYYY-MM-DD');
        params.endDate = this.$moment(this.timeList[1]).format('YYYY-MM-DD');
      }
      if (this.searchParams.orgCodes && this.searchParams.orgCodes.length) {
        params.orgCodes = this.searchParams.orgCodes;
      }
      const {installPosition} = this.searchParams;
      params.installPosition = Array.isArray(installPosition) && installPosition.length > 0 ? this.searchParams.installPosition.at(-1) : '';
      this.axios({
        method: 'post',
        url: '/dms/oee-board/oeeStatistics',
        data: params,
      }).then((res) => {
        if (res.code === 200) {
          this.dataArr = res.data.list;
          this.total = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    //导出
    exportTemplateClick() {
      let params = {
        ...this.searchParams,
      };

      if (this.timeList[1]) {
        params.startDate = this.$moment(this.timeList[0]).format('YYYY-MM-DD');
        params.endDate = this.$moment(this.timeList[1]).format('YYYY-MM-DD');
      }
      if (this.searchParams.orgCodes && this.searchParams.orgCodes.length) {
        params.orgCodes = this.searchParams.orgCodes;
      }
      const {installPosition} = this.searchParams;
      params.installPosition = Array.isArray(installPosition) && installPosition.length > 0 ? this.searchParams.installPosition.at(-1) : '';
      const filName = 'OEE统计';
      this.axios({
        method: 'post',
        url: '/dms/oee-board/exportOeeStatistics',
        responseType: 'blob',
        data: params,
      }).then((res) => {
        fileDownload(res, filName + '.xlsx');
      });
    },
  },
};
</script>

<style scoped lang="scss">
.oeelose {
  .formList {
    padding: 30px;

    .btn {
      margin-top: 20px;
      text-align: center;
      width: 100%;
      height: 40px;
    }

    .inputBorder {
      border: 1px solid #dcdee2;
      border-radius: 4px;
    }
  }
}
</style>

<style lang="scss"></style>
